package com.fengyunhe.manager.service.impl;

import com.fengyunhe.common.RequestThread;
import com.fengyunhe.common.bean.PageList;
import com.fengyunhe.manager.CurrentUser;
import com.fengyunhe.manager.dao.AdminLogDao;
import com.fengyunhe.manager.dao.entity.AdminLogEntity;
import com.fengyunhe.manager.service.AdminLogService;
import com.fengyunhe.common.bean.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@Service
public class AdminLogServiceImpl implements AdminLogService {

    @Autowired
    private AdminLogDao adminLogDao;


    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW) //无论成功失败，日志记录在单独的一个事务中，不受其他事务影响
    public void addLog(String logText,
                       String moduleName, boolean success, Object args[], String msgOrErrorText) {
        CurrentUser currentUser = CurrentUser.get();
        AdminLogEntity log = new AdminLogEntity();
        log.setCreatedByRealName(currentUser.getDisplayName());
        log.setCreatedByUserId(currentUser.getUserId());
        log.setCreatedAt(new Timestamp(System.currentTimeMillis())); //时间
        log.setIp(RequestThread.getVisit().getIp()); //IP
        log.setLogContent(logText); //操作的内容
        log.setModuleName(moduleName); //操作所在的模块
        log.setReturnSuccess(success ? 1 : 0);
        log.setArgs(ToStringBuilder.reflectionToString(args, ToStringStyle.NO_FIELD_NAMES_STYLE));
        if (success) {
            log.setMsgText(msgOrErrorText);
        } else {
            log.setErrorText(msgOrErrorText);
        }
        this.adminLogDao.save(log);

    }

    @Override
    public PageList<AdminLogEntity> findByPage(Page page, String moduleName) {
        String hql = "from AdminLogEntity as log where 1=1 ";
        List<Object> params = new ArrayList<Object>();
        if (StringUtils.isNotBlank(moduleName)) {
            hql += " and log.moduleName like ?";
            params.add("%" + moduleName + "%");
        }
        hql += " order by log.createdAt desc";
        return adminLogDao.findByPage(page, hql, params);
    }


}
